package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import static com.zzyl.common.constant.CacheConstants.ALL_PRODUCT_KEY;

/**
 * 设备Service业务层处理
 *
 * @author zs
 * @date 2025-10-13
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 查询设备
     *
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息
     *
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return deviceMapper.deleteById(id);
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //先从ito中查询产品列表
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        listProductsRequest.setLimit(50);
        ListProductsResponse response = client.listProducts(listProductsRequest);
        List<ProductSummary> products = response.getProducts();
        //将查出来的数据存到redis中
        redisTemplate.opsForValue().set(ALL_PRODUCT_KEY, JSONUtil.toJsonStr(products));
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        String result = redisTemplate.opsForValue().get(ALL_PRODUCT_KEY);

        if (result == null) {
            return Collections.emptyList();
        }

        return JSONUtil.toList(result, ProductVo.class);
    }


    /**
     * 注册设备
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //判断设备名是否重复
        LambdaQueryWrapper<Device> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Device::getDeviceName, deviceDto.getDeviceName());
        long count = count(lqw);
        if (count > 0) {
            throw new RuntimeException("设备名重复");
        }
        //判断设备id是否重复
        LambdaQueryWrapper<Device> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(Device::getProductKey, deviceDto.getProductKey());
        count = count(lqw);
        if (count > 0) {
            throw new RuntimeException("设备id重复");
        }


        if (deviceDto.getLocationType() == 0) {
            deviceDto.setPhysicalLocationType(-1);
        }
        //判断同一位置是否绑定了相同的设备
        LambdaQueryWrapper<Device> lqw2 = new LambdaQueryWrapper<>();
        lqw2.eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .eq(Device::getProductKey, deviceDto.getProductKey());
        count = count(lqw2);
        if (count > 0) {
            throw new RuntimeException("同一位置不能绑定相同的设备");
        }

        //随机生成密钥Secret
        String secret = UUID.randomUUID().toString().replaceAll("-", "");

        //注册设备到华为iot平台
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setNodeId(deviceDto.getNodeId());
        body.setDeviceName(deviceDto.getDeviceName());
        body.setProductId(deviceDto.getProductKey());
        body.setAuthInfo(new AuthInfo().withSecret(secret));

        request.withBody(body);

        AddDeviceResponse response = null;
        try {
            response = client.addDevice(request);
        } catch (Exception e) {
            throw new BaseException("设备注册失败");
        }

        //保存数据到数据库
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(response.getDeviceId());
        device.setSecret(secret);
        save(device);

    }

    /**
     * 获取设备详情
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo getInfo(String iotId) {
        //查询数据库
        Device device = lambdaQuery().eq(Device::getIotId, iotId)
                .one();
        //查询IOT平台，补全缺失的数据（deviceStatus和activeTime）
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        ShowDeviceResponse response = null;
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }

        //数据封装返回
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        deviceDetailVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceDetailVo.setActiveTime(activeTime);
        }
        return deviceDetailVo;

    }

    /**
     * 查询设备上报数据
     */
    @Override
    public AjaxResult queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response = null;
        try {
            response = client.showDeviceShadow(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备上报数据，调用失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        return null;
    }

    /**
     * 修改设备
     *
     * @param deviceDto
     */
    @Override
    public void updateDevice111(DeviceDto deviceDto) {
        //先修改数据库中的数据
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        updateDevice(device);

        ///修改华为云中的数据
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(device.getIotId());
        UpdateDevice body = new UpdateDevice();
        AuthInfoWithoutSecret authInfobody = new AuthInfoWithoutSecret();
        authInfobody.withSecureAccess(true);
        body.withAuthInfo(authInfobody);
        body.withDescription(deviceDto.getRemark());
        body.withDeviceName(deviceDto.getDeviceName());
        request.withBody(body);
        try {
            client.updateDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 修改设备，调用失败");
        }

    }

    /**
     * 删除设备
     * @param itoId
     */
    @Override
    public void DeleteDeviceByIotId(String itoId) {
        //先从数据库删除
        LambdaQueryWrapper<Device> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Device::getIotId, itoId);
        deviceMapper.delete(lqw);
        //从华为云中删除
        DeleteDeviceRequest request=new DeleteDeviceRequest();
        request.withDeviceId(itoId);
        DeleteDeviceResponse respons=null;
        try {
            respons= client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 删除设备，调用失败");
        }
    }


    /**
     * 查询产品详情(报警规则模块使用)
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        return AjaxResult.success(serviceCapabilities);
    }
}
